package org.abratuhi.kvngroupware.network;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public abstract class AbstractClient implements Client, Runnable{
	String id;
	
	Socket socket;
	Thread thread;
	boolean runOk;
	
	MessageProceeder mproceeder;
	
	public AbstractClient(Socket socket, MessageProceeder mproceeder){
		this.socket = socket;
		this.mproceeder = mproceeder;
	}
	
	public synchronized void setId(String id){
		this.id = id;
	}
	
	public synchronized String getId(){
		return this.id;
	}
	
	public void sendMessage(Message message){
		sendString(message.toString());
	}
	public void sendString(String str){
		if (socket != null && !socket.isClosed()){
		try {
			new DataOutputStream(socket.getOutputStream()).writeUTF(str);
		} catch (IOException e) {
			doOnCommunicationError();
		}
		}
	}
	public Message receiveMessage(){
		String strmsg = receiveString();
		return (Message) ((strmsg == null) ? strmsg : Message.fromMessage(strmsg));
	}
	public String receiveString(){
		String strMsg = null;
		if(socket != null && !socket.isClosed()){
		try {
			strMsg = new DataInputStream(socket.getInputStream()).readUTF();
			if(strMsg != null && strMsg != ""){
				return strMsg;
			}
			else{
				return null;
			}
		} catch (IOException e) {
			doOnCommunicationError();
		}
		}
		return null;
	}
	
	public synchronized void start(){
		this.setRunOK(true);
		this.thread = new Thread(this);
		this.thread.start();
	}
	
	public synchronized void stop(){
		setRunOK(false);
		thread.interrupt();
	}
	
	public void register(){
		
	}
	
	public void unregister(){
		
	}
	
	public synchronized Socket getSocket(){
		return this.socket;
	}
	
	public synchronized boolean getRunOK(){
		return this.runOk;
	}
	
	public synchronized void setRunOK(boolean run){
		this.runOk = run;
	}
	
	public synchronized void switchRunOK(){
		this.runOk = (this.runOk == true)? false:true;
	}

}
